﻿@inject CodeSnippetService CodeSnippetService
@inherits IdComponentBase
@implements IAsyncDisposable

<div style="height:370px; width:740px;">
    <canvas id="@Id"></canvas>
</div>

<Button class="mt-3" Text="Randomize" OnClick="Randomize" />

<h4><code>JavaScript Code</code></h4>
<Pre>@Code</Pre>

@code {
    /// <summary>
    /// JS 互操作实例
    /// </summary>
    private IJSObjectReference? Module { get; set; }

    /// <summary>
    /// Random 随机数生成器
    /// </summary>
    private Random Random { get; } = new();

    /// <summary>
    /// JS 代码段
    /// JS Code
    /// </summary>
    private string? Code { get; set; }

    /// <summary>
    /// <inheritdoc />
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        Code = await CodeSnippetService.GetFileContentAsync("Demos\\Charts\\Line\\LineChartJS.razor.js");
    }

    /// <summary>
    /// <inheritdoc />
    /// 动态导入JS模块，初始化Chart
    /// Dynamically import JS module and initialize Chart
    /// </summary>
    /// <param name="firstRender"></param>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            Module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/BootstrapBlazor.Shared/Demos/Charts/Line/LineChartJS.razor.js");

            //随机生成一组数据
            //Randomly generate a set of data
            var chartData = Enumerable.Range(1, 7).Select(_ => Random.Next(25, 85)).ToArray();
            await Module.InvokeVoidAsync("lineChart", Id, chartData);
        }
    }

    private async Task Randomize()
    {
        //随机生成一组数据
        //Randomly generate a set of data
        var chartData = Enumerable.Range(1, 7).Select(_ => Random.Next(25, 85));
        if (Module != null)
        {
            await Module.InvokeVoidAsync("randomize", Id, chartData);
        }
    }

    private async ValueTask Dispose(bool disposing)
    {
        if (disposing)
        {
            if (Module != null)
            {
                await Module.InvokeVoidAsync("dispose", Id);
                await Module.DisposeAsync();
            }
        }
    }

    /// <summary>
    /// 释放资源
    /// DisposeAsync
    /// </summary>
    public async ValueTask DisposeAsync()
    {
        await Dispose(true);
        GC.SuppressFinalize(this);
    }
}
